package com.netease.cloud.cm.util;

import com.netease.cloud.cm.api.AlarmService;
import com.netease.cloud.cm.retrofit.service.RetrofitManager;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * 报警通知消息发送工具类
 */
@Slf4j
public class AlarmAlertUtils {

	private static AlarmService service = RetrofitManager.getAlarmService();

	public static void sendAlarm(String content, boolean isms) {

		boolean smsEnable = "true".equals(CommonStringUtils.getConfig("sms.enable"));
		boolean popoEnable = "true".equals(CommonStringUtils.getConfig("popo.enable"));

		String phoneReceivers = CommonStringUtils.getConfig("phones");
		String emailReceivers = CommonStringUtils.getConfig("emails");
		String ak = CommonStringUtils.getConfig("alarm.ak");

		if (smsEnable && isms) {
			try {
				Calendar now = Calendar.getInstance();
				now.setTime(new Date());
				// 短信发送的时间段为非工作时间段
				if (now.get(Calendar.HOUR_OF_DAY) < 9 || now.get(Calendar.HOUR_OF_DAY) > 20) {
					Response<ResponseBody> result = service.sendSMS(phoneReceivers, content, ak, CommonStringUtils.getRandomString(10)).execute();
					if (!result.isSuccessful()) {
						log.error("[AlarmAlertUtils] send sms failed");
					}
				}
			} catch (IOException e) {
				log.error("[AlarmAlertUtils] send sms error", e);
			}
		}

		if (popoEnable) {
			try {
				Response<ResponseBody> result = service.sendPOPO(emailReceivers, content, ak, CommonStringUtils.getRandomString(10)).execute();
				if (!result.isSuccessful()) {
					log.error("[AlarmAlertUtils] send popo failed");
				}
			} catch (IOException e) {
				log.error("[AlarmAlertUtils] send popo error", e);
			}
		}
	}
}
